package com.h3bpm.web.common.utils;

import com.h3bpm.web.common.domin.EsbReqHead;
import com.h3bpm.web.common.domin.EsbResHead;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.*;

/**
 * 自定义http类
 *
 */
public class HttpLocalUtils {

    private static Logger logger = Logger.getLogger(HttpLocalUtils.class);


    public static String doPost(String url, Map<String, Object> map, String contentType, String authorization) {
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
        HttpMethodParams params = postMethod.getParams();
        params.setContentCharset("UTF-8");

        postMethod.addRequestHeader("accept", "*/*");
        postMethod.addRequestHeader("connection", "Keep-Alive");
        //设置json格式传送
        if (contentType == null || "".equals(contentType)) {
            postMethod.addRequestHeader("Content-Type", "application/json;charset=utf-8");
        } else {
            postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        }
        if (authorization == null || "".equals(authorization)) {
        } else {
            postMethod.addRequestHeader("Authorization", authorization);
        }
        //必须设置下面这个Header
        postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
        //添加请求参数
        Set<Map.Entry<String, Object>> entrySet = map.entrySet();
        // 循环遍历，获取迭代器
        Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Object> mapEntry = iterator.next();
            postMethod.addParameter(mapEntry.getKey(), mapEntry.getValue().toString());
        }

        String res = "";
        try {
            int code = httpClient.executeMethod(postMethod);
            if (code == 200) {
                res = postMethod.getResponseBodyAsString();

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }

    public static String sendHttpPost(String url, String jsonBody, String authorization) {
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
            httpPost.addHeader("Authorization", authorization);
            httpPost.setEntity(new StringEntity(jsonBody));
            CloseableHttpResponse response = null;

            response = httpClient.execute(httpPost);

            //  System.out.println(response.getStatusLine().getStatusCode() + "\n");
            HttpEntity entity = response.getEntity();
            String responseContent = EntityUtils.toString(entity, "UTF-8");
            //  System.out.println(responseContent);
            response.close();
            httpClient.close();

            return responseContent;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 以post方式调用第三方接口
     *
     * @param url
     * @param json
     * @return
     */
    private static CloseableHttpClient httpClient = null;

    //private static String tokenString = "Bearer B537F8B88ABE48EF958DFB0E4DD28E89";
    public static String doPost2(String url, String json, String authorization) {
        try {
            httpClient = HttpClientBuilder.create().build();
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5000)
                    .setSocketTimeout(2000).setConnectTimeout(2000).build();
            HttpPost post = new HttpPost(url);
            post.setConfig(requestConfig);
            post.addHeader("Content-Type", "application/json;charset=utf-8");
            //post.addHeader("Authorization", authorization);
            StringEntity s = new StringEntity(json, Charset.forName("UTF-8"));
            s.setContentEncoding("UTF-8");
            //发送json数据需要设置contentType
            //设置请求参数
            post.setEntity(s);
            HttpResponse response = httpClient.execute(post);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                //返回json格式
                String res = EntityUtils.toString(response.getEntity());
                return res;
            }
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
                //返回json格式
                String res = EntityUtils.toString(response.getEntity());
                return res;
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * HTTP发送post、put请求，带header、body的方法，获取结果
     *
     * @param url
     * @param requestMethod POST、PUT
     * @param
     * @param
     * @return
     * @author yswKnight
     */
    public static String httpRequest(String url, String requestMethod, String authorization, String params) {
        logger.info("<><><>进入http请求工具包。。 url:" + url);
        String result = "";
        HttpURLConnection connection = null;
        BufferedReader in = null;
        OutputStreamWriter outer = null;
        InputStream ips = null;
        StringBuffer buffer = null;

        try {
            URL restURL = new URL(url);
            connection = (HttpURLConnection) restURL.openConnection();
            connection.setRequestMethod(requestMethod);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            //循环增加header

            connection.setRequestProperty("Authorization", authorization);


            outer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            //outer.write(params);
            outer.flush();
            outer.close();
            logger.info("<><><>读取参数结束");

            connection.connect();
            ips = connection.getInputStream();
            logger.info("打印读取流：{}" + ips);
            System.out.println("new String(ips) = " + ips.toString());

            in = new BufferedReader(new InputStreamReader(ips, "UTF-8"));
            buffer = new StringBuffer();
            String line = "";
            while ((line = in.readLine()) != null) {
                buffer.append(line);
                buffer.append("\r\n");
                logger.info("读取参数：{}" + line);
            }
            in.close();
            ips.close();
            //得到结果
            result = buffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            connection.disconnect();
        }
        return result;
    }

    public static String httpURLPOSTCase(String methodUrl, String body, String Authorization) {
        HttpURLConnection connection = null;
        OutputStream dataout = null;
        BufferedReader reader = null;
        String line = null;
        try {
            URL url = new URL(methodUrl);
            connection = (HttpURLConnection) url.openConnection();// 根据URL生成HttpURLConnection
            connection.setDoOutput(true);// 设置是否向connection输出，因为这个是post请求，参数要放在http正文内，因此需要设为true,默认情况下是false
            connection.setDoInput(true); // 设置是否从connection读入，默认情况下是true;
            connection.setRequestMethod("POST");// 设置请求方式为post,默认GET请求
            connection.setUseCaches(false);// post请求不能使用缓存设为false
            connection.setConnectTimeout(3000);// 连接主机的超时时间
            connection.setReadTimeout(3000);// 从主机读取数据的超时时间
            connection.setInstanceFollowRedirects(true);// 设置该HttpURLConnection实例是否自动执行重定向
            connection.setRequestProperty("connection", "Keep-Alive");// 连接复用
            connection.setRequestProperty("charset", "utf-8");

            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Authorization", Authorization);
            connection.connect();// 建立TCP连接,getOutputStream会隐含的进行connect,所以此处可以不要

            dataout = new DataOutputStream(connection.getOutputStream());// 创建输入输出流,用于往连接里面输出携带的参数
            dataout.write(body.getBytes());
            dataout.flush();
            dataout.close();
            System.out.println(connection.getResponseCode());
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));// 发送http请求
                StringBuilder result = new StringBuilder();
                // 循环读取流
                while ((line = reader.readLine()) != null) {
                    result.append(line).append(System.getProperty("line.separator"));//
                }
                System.out.println(result.toString());
                return String.valueOf(result);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
           /* try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            connection.disconnect();*/
        }
        return null;
    }

    public static String doPostToESB(String url, String json, EsbReqHead esbReqHead) {
        logger.info("请求ESB信息,url:"+url+", sourceSystem："+esbReqHead.get(EsbReqHead.source_System)
                +", targetSystem："+esbReqHead.get(EsbReqHead.target_System)
                +", requestId："+esbReqHead.get(EsbReqHead.request_Id)
                +", serviceName："+esbReqHead.get(EsbReqHead.service_Name));
        try {
            httpClient = HttpClientBuilder.create().build();
//            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5000)
//                    .setSocketTimeout(2000).setConnectTimeout(2000).build();
            HttpPost post = new HttpPost(url);
//            post.setConfig(requestConfig);
            post.addHeader(EsbReqHead.source_System, (String)esbReqHead.get(EsbReqHead.source_System));
            post.addHeader(EsbReqHead.target_System, (String)esbReqHead.get(EsbReqHead.target_System));
            post.addHeader(EsbReqHead.request_Id, (String)esbReqHead.get(EsbReqHead.request_Id));
            post.addHeader(EsbReqHead.service_Name, (String)esbReqHead.get(EsbReqHead.service_Name));
            //post.addHeader("Authorization", authorization);
            StringEntity s = new StringEntity(json, Charset.forName("UTF-8"));
            s.setContentEncoding("UTF-8");
            //发送json数据需要设置contentType
            //设置请求参数
            post.setEntity(s);
            HttpResponse response = httpClient.execute(post);
            org.apache.http.Header[] statusFlags = response.getHeaders(EsbResHead.status_Flag);
            if (statusFlags[0].getValue().equals("1")) {
                //返回json格式
                String res = EntityUtils.toString(response.getEntity());
                return res;
            }
            if (statusFlags[0].getValue().equals("0")) {
                //返回json格式
                String res = EntityUtils.toString(response.getEntity());
                logger.error(String.format("请求失败url：%s,结果res", url, res));
                return res;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

   /* public static void main(String[] args) {
        String sql= "{\"deptName\":\"同济咨询.TJEC咨询一所.TJEC咨询一所二部\",\"originatorName\":\"沈翔\",\"deptId\":\"128be667-b1f8-11ea-850c-e454e8d955a8\",\"intanceName\":\"咨询成 果文件校审单.26\",\"bizObjectId\":\"8b33747e-3c23-4631-a6fe-8bb76475595e\",\"originator\":\"H04-00031\",\"type\":1,\"bizObjectSchemaCode\":\"ConsultingOutcomeDocument\",\"url\":\"http://10.66.37.180/Portal/InstanceSheets.html?InstanceId=33b8ef44-1b3f-40ff-800c-6efebbcc352d&flag=3\",\"intanceId\":\"33b8ef44-1b3f-40ff-800c-6efebbcc357d\",\"h5url\":\"http://10.66.37.180/Portal/InstanceSheets.html?InstanceId=33b8ef44-1b3f-40ff-800c-6efebbcc362d&flag=3\",\"instanceState\":0,\"projectLeaderId\":\"66893A3E-EE60-4DCE-8BE9-06064AFBD152\",\"projectLeader\":\"沈翔\",\"businessCategoryId\":\"4196c290-82de-11ea-b423-00163e0c795f\",\"businessCategory\":\"项目建议书编制\",\"projectName\":\"上海市虹口区四川北路HK194-01地块项目节能\",\"projectId\":\"6249f5b9-b184-11ea-850c-e454e8d955a8\"}";
        String url="http://10.66.37.181:8088/prod-api/workflow/addWorkflow";
        String s = doPost2(url, sql, "");
        System.out.println(s);
        System.out.println("Charset——————————————————-"+Charset.defaultCharset().name());
        System.out.println("file.encoding——————————————————-"+System.getProperty("file.encoding"));

    }*/
}


